from .models import SystemPermission, SystemRole, SystemRolePermission

from rest_framework import serializers


class SystemPermissionSerializer(serializers.Serializer):
	id = serializers.IntegerField(read_only=True)
	path = serializers.CharField()
	route_name = serializers.CharField()
	title = serializers.CharField()
	url = serializers.CharField()
	parent_id = serializers.PrimaryKeyRelatedField(queryset=SystemPermission.objects.all())
	sort = serializers.IntegerField()
	type = serializers.CharField()
	children = serializers.SerializerMethodField()
	status = serializers.BooleanField()

	class Meta:
		model = SystemPermission

	def get_children(self, obj):
		return SystemPermissionSerializer(SystemPermission.objects.filter(parent_id=obj.id, deleted=False, status=True),
										  many=True).data


class SystemPermissionTreeSerializer(serializers.Serializer):
	id = serializers.IntegerField(read_only=True)
	path = serializers.CharField()
	route_name = serializers.CharField()
	title = serializers.CharField()
	url = serializers.CharField()
	parent_id = serializers.PrimaryKeyRelatedField(queryset=SystemPermission.objects.all())
	sort = serializers.IntegerField()
	type = serializers.CharField()
	children = serializers.SerializerMethodField()
	status = serializers.BooleanField()

	class Meta:
		model = SystemPermission

	def get_children(self, obj):
		role_id = self.context.get('role')
		data = SystemPermission.objects.filter(parent_id=obj.id, deleted=False, status=True)\
			.filter(id__in=SystemRolePermission.objects.filter(role_id=role_id).values_list('permission_id')).order_by('sort')
		return SystemPermissionSerializer(data, many=True).data


class SystemRoleTreeSerializer(serializers.ModelSerializer):
	perms_str = serializers.SerializerMethodField()
	ids = serializers.SerializerMethodField()

	class Meta:
		model = SystemRole
		exclude = ['deleted']

	def get_perms_str(self, obj):
		data = SystemRolePermission.objects.filter(role_id=obj.id)
		permissions = []
		for d in data:
			permissions.append(d.permission.title)
		perms = ','.join(permissions)
		return perms

	def get_ids(self, obj):
		data = SystemRolePermission.objects.filter(role_id=obj.id)
		permissions = []
		for d in data:
			permissions.append(d.permission.id)
		return permissions


class SystemRoleSerializer(serializers.ModelSerializer):

	class Meta:
		model = SystemRole
		fields = ['id', 'name']
